package com.dean.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Properties;
/**
 * @ClassName PropertyUtils
 * @Description properties 工具类
 * @Author dean
 * @Date 2021/10/3 10:03
 */
public class PropertyUtils {

    private static final Logger logger = LoggerFactory.getLogger(PropertyUtils.class);

    /**
     *  读取配置文件
     * @param filePath
     */
    public static Properties readProperties(String filePath) {
        Properties properties = null;
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(filePath);
            properties = new Properties();
            properties.load(new InputStreamReader(inputStream, "UTF-8"));
        } catch (IOException e) {
            logger.error("配置文件读取异常",e.getMessage(),e);
        } finally{
            try {
                if(inputStream != null){
                    inputStream.close();
                }
            } catch (IOException e) {
                logger.error("配置文件读取异常",e.getMessage(),e);
            }
        }
        return properties;
    }

    /**
     * 保存配置文件
     * @param filePath
     * @param properties
     * @return
     */
    public static boolean saveProperties(String filePath,Properties properties){
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(filePath);
            properties.store(out, "dbserve init properties");
        } catch (IOException e1) {
            logger.error("保存配置文件失败:{}",e1.getMessage(),e1);
            return false;
        }finally {
            if(out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(),e);
                }
            }
        }
        return true;
    }
}
